<template>
  <v-container>
    <v-row>
      <v-col>
        <v-data-table
          :headers="headers"
          :items="toolList"
          group-by="drawer"
          class="elevation-1"
        >
          <template v-slot:top>
            <v-toolbar flat>
              <v-toolbar-title>工具列表</v-toolbar-title>
              <v-divider class="mx-4" inset vertical></v-divider>
              <v-spacer></v-spacer>
              <v-dialog v-model="dialog" max-width="300px" persistent>
                <template v-slot:activator="{ on, attrs }">
                  <v-btn
                    color="primary"
                    dark
                    class="mb-2"
                    v-bind="attrs"
                    v-on="on"
                  >
                    添加
                  </v-btn>
                </template>
                <v-card class="pa-6">
                  <v-card-title>
                    <span class="text-h5">{{ formTitle }}</span>
                  </v-card-title>

                  <v-form ref="form" v-model="valid" lazy-validation>
                    <v-text-field
                      v-model="editedItem.name"
                      label="名称"
                      :rules="nameRules"
                      :counter="100"
                    ></v-text-field>

                    <v-select
                      v-model="editedItem.type"
                      :items="
                        toolTypes.map((item) => ({
                          text: item.name,
                          value: item.id,
                        }))
                      "
                      label="工具类型"
                      :rules="[(v) => !!v || '必须选择一个工具类型']"
                    >
                    </v-select>

                    <v-select
                      v-model="editedItem.drawer"
                      :items="
                        drawerList.map((item) => ({
                          text: item.name,
                          value: item.id,
                        }))
                      "
                      label="所属抽屉"
                      :rules="[(v) => !!v || '必须选择一个所属抽屉']"
                    >
                    </v-select>

                    <v-menu
                      class="datepicker-menu"
                      ref="menu"
                      v-model="showExpireDatePicker"
                      :close-on-content-click="false"
                      transition="scale-transition"
                      offset-y
                      min-width="auto"
                    >
                      <template v-slot:activator="{ on, attrs }">
                        <v-text-field
                          class="mr-4 mt-5"
                          style="width: 200px; flex: none; background: none"
                          v-model="editedItem.expireDate"
                          placeholder="到期时间"
                          append-icon="mdi-calendar-clock"
                          clear-icon="mdi-close-circle"
                          readonly
                          clearable
                          rows="1"
                          v-bind="attrs"
                          v-on="on"
                        ></v-text-field>
                      </template>
                      <v-date-picker
                        v-model="editedItem.expireDate"
                        :allowed-dates="allowedDates"
                        no-title
                        scrollable
                        :show-current="false"
                        @input="showExpireDatePicker = false"
                        :day-format="(date) => date.split('-')[2]"
                        locale="zh-cn"
                      >
                      </v-date-picker>
                    </v-menu>
                  </v-form>
                  <v-alert
                    type="warning"
                    outlined
                    prominent
                    border="left"
                    v-model="pendingAddTool"
                  >
                    请将要添加的工具放在射频信号接收区...
                  </v-alert>
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" text @click="close">
                      取消
                    </v-btn>
                    <v-btn
                      :disabled="!valid"
                      :loading="pendingAddTool"
                      color="blue darken-1"
                      text
                      @click="save"
                    >
                      保存
                    </v-btn>
                  </v-card-actions>
                </v-card>
              </v-dialog>
              <v-dialog v-model="dialogDelete" max-width="300px">
                <v-card>
                  <v-card-title class="text-h6"
                    >确定要删除这条记录吗？</v-card-title
                  >
                  <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue darken-1" text @click="closeDelete"
                      >取消</v-btn
                    >
                    <v-btn color="blue darken-1" text @click="deleteItemConfirm"
                      >确定</v-btn
                    >
                    <v-spacer></v-spacer>
                  </v-card-actions>
                </v-card>
              </v-dialog>
            </v-toolbar>
          </template>
          <template v-slot:[`group.header`]="{ group }">
            <v-card class="d-flex pa-2" flat>
              {{ drawerList.find((item) => item.id == group).name }}
            </v-card>
          </template>
          <template v-slot:[`item.type`]="{ item }">
            <div
              v-text="
                toolTypes.find((itemToFind) => itemToFind.id == item.type).name
              "
            ></div>
          </template>
          <template v-slot:[`item.drawer`]="{ item }">
            <div
              v-text="
                drawerList.find((itemToFind) => itemToFind.id == item.drawer)
                  .name
              "
            ></div>
          </template>
          <template v-slot:[`item.expireDate`]="{ item }">
            <div v-text="item.expireDate"></div>
          </template>
          <template v-slot:[`item.daysRemaining`]="{ item }">
            <span v-if="item.expireDate !== null" :class="{ 'red': expired(item.expireDate) }">
              {{ dateDifference(item.expireDate) }}
            </span>
            <span v-else>-</span>
          </template>
          <template v-slot:[`item.actions`]="{ item }">
            <v-icon small class="mr-2" @click="editItem(item)">
              mdi-pencil
            </v-icon>
            <v-icon small @click="deleteItem(item)"> mdi-delete </v-icon>
          </template>
          <template v-slot:no-data> 没有数据！ </template>
        </v-data-table>
      </v-col>
    </v-row>
    <v-row>
      <v-col>
        <v-snackbar
          v-if="!failed"
          v-model="alert"
          :timeout="3000"
          color="success"
        >
          {{ info }}
        </v-snackbar>
        <v-snackbar v-else v-model="alert">
          {{ info }}

          <template v-slot:action="{ attrs }">
            <v-btn color="red" text v-bind="attrs" @click="alert = false">
              关闭
            </v-btn>
          </template>
        </v-snackbar>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  data: () => ({
    dialog: false,
    dialogDelete: false,
    headers: [
      {
        text: "类型",
        align: "start",
        sortable: false,
        value: "type",
      },
      { text: "名称", value: "name" },
      { text: "标识码", value: "identifier" },
      { text: "所属抽屉", value: "drawer" },
      { text: "到期时间", value: "expireDate" },
      { text: "剩余有效天数", value: "daysRemaining" },
      { text: "动作", value: "actions", sortable: false },
    ],
    toolTypes: [
      {
        id: 1,
        name: "钳子",
      },
      {
        id: 2,
        name: "改锥",
      },
      {
        id: 3,
        name: "扳手",
      },
    ],
    drawerList: [
      {
        id: 1,
        name: "抽屉一",
      },
      {
        id: 2,
        name: "抽屉二",
      },
      {
        id: 3,
        name: "抽屉三",
      },
    ],
    toolList: [
      {
        type: 1,
        name: "尖嘴钳",
        drawer: 1,
        identifier: "AA",
        expireDate: null,
      },

      {
        type: 2,
        name: "十字改锥",
        drawer: 1,
        identifier: "BB",
        expireDate: null,
      },
      {
        type: 3,
        name: "14mm",
        drawer: 1,
        identifier: "CC",
        expireDate: null,
      },
      {
        type: 1,
        name: "斜口钳",
        drawer: 2,
        identifier: "DD",
        expireDate: null,
      },
      {
        type: 2,
        name: "一字改锥",
        drawer: 2,
        identifier: "EE",
        expireDate: null,
      },
      {
        type: 3,
        name: "16mm",
        drawer: 2,
        identifier: "FF",
        expireDate: "2024-8-2",
      },
      {
        type: 1,
        name: "管钳",
        drawer: 3,
        identifier: "GG",
        expireDate: null,
      },
      {
        type: 2,
        name: "星型改锥",
        drawer: 3,
        identifier: "HH",
        expireDate: null,
      },
      {
        type: 3,
        name: "梅花扳手",
        drawer: 3,
        identifier: "II",
        expireDate: null,
      },
    ],
    editedIndex: -1,
    editedItem: {
      type: 0,
      name: "",
      drawer: 0,
      identifier: "",
      expireDate: null,
    },
    defaultItem: {
      type: 0,
      name: "",
      drawer: 0,
      identifier: "",
      expireDate: null,
    },
    valid: true,
    nameRules: [
      (v) => !!v || "名称不能为空",
      (v) => (v && v.length <= 100) || "名称必须小于100个字符",
    ],
    alert: false,
    info: "",
    failed: false,
    pendingAddTool: false,
    showExpireDatePicker: false,
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? "添加工具" : "编辑工具";
    },
  },

  watch: {
    dialog(val) {
      val || this.close();
    },
    dialogDelete(val) {
      val || this.closeDelete();
    },
  },

  methods: {
    editItem(item) {
      this.editedIndex = this.toolList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
    },

    deleteItem(item) {
      this.editedIndex = this.toolList.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialogDelete = true;
    },

    deleteItemConfirm() {
      this.toolManage.delTool(this.editedItem.id).then((retVal) => {
        if (retVal === true) {
          this.closeDelete();

          this.info = "删除成功";
          this.failed = false;
          this.alert = true;

          this.toolManage
            .getToolList()
            .then((retVal) => (this.toolList = JSON.parse(retVal)));
        } else {
          this.closeDelete();

          this.info = "删除失败";
          this.failed = true;
          this.alert = true;
        }
      });
    },

    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
        this.$refs.form.reset();
      });
    },

    closeDelete() {
      this.dialogDelete = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },

    save() {
      if (this.$refs.form.validate()) {
        if (this.editedIndex > -1) {
          this.toolManage
            .modifyTool(
              this.editedItem.id,
              this.editedItem.type,
              this.editedItem.name,
              this.editedItem.drawer,
              this.editedItem.expireDate
            )
            .then((retVal) => {
              if (retVal === true) {
                this.close();

                this.info = "修改成功";
                this.failed = false;
                this.alert = true;

                this.toolManage
                  .getToolList()
                  .then((retVal) => (this.toolList = JSON.parse(retVal)));
              } else {
                this.info = "修改失败";
                this.failed = true;
                this.alert = true;
              }
            });
        } else {
          this.pendingAddTool = true;
          this.toolManage.addTool(
            this.editedItem.type,
            this.editedItem.name,
            this.editedItem.drawer,
            this.editedItem.expireDate
          );
        }
      }
    },

    onToolAdded(succeed, errInfo) {
      if (succeed) {
        this.close();

        this.pendingAddTool = false;

        this.info = "添加成功";
        this.failed = false;
        this.alert = true;

        this.toolManage
          .getToolList()
          .then((retVal) => (this.toolList = JSON.parse(retVal)));
      } else {
        this.pendingAddTool = false;

        this.info = "添加失败，原因：" + errInfo;
        this.failed = true;
        this.alert = true;
      }
    },

    allowedDates: (val) => {
      let cur = new Date(val).getTime();
      let now = new Date().getTime();
      return cur > now;
    },

    dateDifference(expireDate) {
      let dateSpan, iDays;
      dateSpan = Date.parse(expireDate) - new Date();
      iDays = Math.ceil(dateSpan / (24 * 3600 * 1000));
      return iDays;
    },

    expired(expireDate) {
      return this.dateDifference(expireDate) <= 0;
    },
  },
  mounted: async function () {
    this.toolManage.toolAdded.connect(this.onToolAdded);

    this.toolTypes = JSON.parse(await this.toolManage.getToolTypes());
    this.drawerList = JSON.parse(await this.toolManage.getDrawerList());
    this.toolManage
      .getToolList()
      .then((retVal) => (this.toolList = JSON.parse(retVal)));
  },
  unmounted: function () {
    this.toolManage.toolAdded.disconnect(this.onToolAdded);
  },
};
</script>
